package com.seven.restaurant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seven.restaurant.entity.po.OrderPO;
import com.seven.restaurant.entity.request.OrderRequest;
import com.seven.restaurant.entity.vo.OrderDetailsVO;
import com.seven.restaurant.exception.ValidationException;
import com.seven.restaurant.mapper.OrderItemMapper;
import com.seven.restaurant.mapper.OrderMapper;
import com.seven.restaurant.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author BaiBan
 * @since 2022-07-19
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements OrderService {

    @Autowired
    OrderMapper mapper;

    @Autowired
    OrderItemMapper OrderItemMapper;

    @Override
    public OrderDetailsVO get(Long id) {
        OrderDetailsVO detailsVO = mapper.selectDetailsOne(id);
        detailsVO.setItems(OrderItemMapper.selectVO(id));
        return detailsVO;
    }

    @Override
    public IPage<OrderDetailsVO> list(Integer current) {
        Page<OrderDetailsVO> page = new Page<>(current, 10);

        QueryWrapper<OrderPO> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("serve", "pay").orderByDesc("create_time")  // 按照上菜情况，支付情况升序排列，创建时间降序排列
                .eq("del", 0);
        return mapper.selectDetailsPage(page, wrapper);
    }

    @Override
    public Long save(OrderRequest OrderRequest) throws ValidationException {

        Integer table = OrderRequest.getTableId();
        Long userId = OrderRequest.getUserId();
        if ((table == null && userId == null) || (table != null && userId != null))
            throw new ValidationException("桌号和用户编号必须且只能有一个");
        OrderPO OrderPO = toOrderPO(OrderRequest);
        mapper.insert(OrderPO);
        return OrderPO.getId();
    }

    @Override
    public Boolean update(Long id, String type) {
        UpdateWrapper<OrderPO> uw = new UpdateWrapper<>();
        uw.set(type, 1)
                .eq("id", id);
        return mapper.update(null, uw) == 1;
    }

    /**
     * Order类 {@link OrderRequest} 转化成 {@link OrderPO}
     */
    private OrderPO toOrderPO(OrderRequest request) {
        OrderPO po = new OrderPO();
        po.setTableId(request.getTableId());
        po.setUserId(request.getUserId());
        return po;
    }
}
